package org.example.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.json.JSONObject;

import java.util.TreeMap;

/**
 * @description: ID生成工具类，主要采用雪花算法生成ID
 * @author: 谢超
 * @date: 2023/8/14 16:39
 */
@Slf4j
public class IDUtil {

    /**
     * 调用雪花算法生成器对象
     */
    private static SnowflakeShardingKeyGenerator shardingKeyGenerator = new SnowflakeShardingKeyGenerator();

    /**
     * 雪花算法生成器，生成唯一ID
     * @return
     */
    public static Comparable<?> geneSnowFlakeID () {
        return shardingKeyGenerator.generateKey();
    }

    /**
     * 生成设备唯一ID
     * @return
     */
    public static String getDeviceId(JSONObject jsonObject) {
        TreeMap<String, String> treeMap = new TreeMap<>();

        try {
            treeMap.put("id", jsonObject.getString("ip"));
            treeMap.put("event",jsonObject.getString("event"));
            treeMap.put("bizId",jsonObject.getString("bizId"));
            String userAgent = jsonObject.getJSONObject("data").getString("user-agent");
            treeMap.put("userAgent",userAgent);
            return CommonUtil.MD5(treeMap.toString());
        } catch (Exception e) {
            log.error("生成唯一deviceid异常:{}",jsonObject);
            return null;
        }
    }
}
